package com.blogSystem.user.service;

import com.blogSystem.user.dao.ConcerMapper;
import com.blogSystem.user.dao.UserDao;
import com.blogSystem.user.pojo.Concer;
import com.blogSystem.user.pojo.User;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import util.IdWorker;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ConcerMapper concerMapper;

    @Autowired(required = false)
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);
        this.redisTemplate = redisTemplate;
    }



    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
     private BCryptPasswordEncoder encoder;
    /**
     * 发送验证码业务，用于注册
     * @param mobile
     */
    public void sendSms(String mobile){
        //生成6位数字随机数
       String checkcode= RandomStringUtils.randomNumeric(6);
       //向缓存放入一份
        String key="checkcode_"+mobile;
        redisTemplate.opsForValue().set(key,checkcode,5, TimeUnit.MINUTES);
        System.out.println("key:"+key);
        System.out.println(redisTemplate.opsForValue().get(key));

        //给用户发送一份
        Map <String,String> map = new HashMap<String ,String>();
        map.put("mobile",mobile);
        map.put("checkcode",checkcode);
        rabbitTemplate.convertAndSend("sms",map);
    }

    /**
     * 发送验证码业务，用于改密码
     * @param mobile
     */
    public void SendSmsChange(String mobile)
    {
        //生成6位数字随机数
        String changecode= RandomStringUtils.randomNumeric(6);
        //向缓存放入一份
        String key="changecode_"+mobile;
        redisTemplate.opsForValue().set(key,changecode,5, TimeUnit.MINUTES);
        System.out.println("key:"+key);
        System.out.println(redisTemplate.opsForValue().get(key));

        //给用户发送一份
        Map <String,String> map = new HashMap<String ,String>();
        map.put("mobile",mobile);
        map.put("changecode",changecode);
        rabbitTemplate.convertAndSend("sms_change",map);
    }

    //判断手机是否重复
    public boolean mobileIsRep(String mobie){

        User user=userDao.findByMobile(mobie);
        if(user!=null ){
            return true;
        }
        else return false;
    }
    //判断用户名是否重复
    public boolean userNameIsRep(String username){

        User user=userDao.findByUsernameAndRole(username,"ROLE_USER");
        if(user!=null ){
            return true;
        }
        else return false;
    }
    //添加用户
    public void add(User user){
        user.setId(idWorker.nextId()+"");
        //加密
        user.setPassword(encoder.encode(user.getPassword()));
        user.setConcern(0);
        user.setFans(0);
        user.setGender(2);
        user.setRegdate(new Date());
        user.setRole("ROLE_USER");

        userDao.save(user);
    }
    //登录
    public User login(User user){
        User userlog= userDao.findByUsernameAndRole(user.getUsername(),"ROLE_USER");

        //拿数据库中密码和用户密码看是否匹配
        if(userlog!=null&&encoder.matches(user.getPassword(),userlog.getPassword())){
            return userlog;
        }
        return null;
    }


    public List<User> findAll(){

        return userDao.findAll();
    }

    /**
     * 查找
     * @param id
     * @return
     */
    public User findById(String id){
      System.out.println(id);
        return userDao.findById(id).get();
    }


    /**
     * 根据名字查询
     *
     * @return
     */
    public User searchUser(String username){
        return userDao.findByUsernameAndRole(username,"ROLE_USER");
    }



    /**
     * 注销
     * @param id
     */

    public void delete(String id){
        userDao.deleteById(id);
    }

    /**
     * 修改名字
     * @param id
     * @param newUser
     * @return
     */
    public boolean changeName(String id,User newUser){
        User oldUser=userDao.findById(id).get();
        if(newUser.getUsername()!=null&&!newUser.getUsername().equals("")){
            if(userDao.findByUsernameAndRole(newUser.getUsername(),"ROLE_USER")==null){
                oldUser.setUsername(newUser.getUsername());
                userDao.save(oldUser);
                return true;
            }else {
                return false;
            }
        }
        return false;
    }

public List<String> concerlist(String id){
  List<Concer> concers=concerMapper.selectfans(id);
 if (concers.isEmpty()){
   return null;
 }
 List<String> list=new ArrayList<>();
  for(Concer concer:concers){
    list.add(concer.getConcered_id());
  }
  return list;
}

  public List<String> fanslist(String id){
    List<Concer> concers=concerMapper.selectconcered(id);
    if (concers.isEmpty()){
      return null;
    }
    List<String> list=new ArrayList<>();
    for(Concer concer:concers){
      list.add(concer.getFans_id());
    }
    return list;
  }

  public void concersomeone(Concer concer){
      concerMapper.insert(concer);
  }
  public void deletesomeone(Concer concer){
      concerMapper.deleteById(concer);
  }
    /**
     * 根据名字模糊条件查询
     *
     * @return
     */
    public Page<User> findSearch(String username, int page, int size){
        Pageable pageable= PageRequest.of(page-1,size);
        return userDao.findAllByUsernameLikeAndRole(username,"ROLE_USER"
        ,pageable );
    }
    /**
     * 查询所有
     *
     * @return
     */
    public Page<User> findAll( int page, int size){
        Pageable pageable= PageRequest.of(page-1,size);
        return userDao.findAllByRole("ROLE_USER",pageable) ;
    }

    /**
     * 批量删除
     * @param ids
     */
    public void deleteList(List<String> ids){
        userDao.deleteUserByIdIn(ids);
    }


    /**
     * 修改密码
     * @param newUser
     */
    public void changePass(User newUser){
        User oldUser=userDao.findById(newUser.getId()).get();
        if(newUser.getPassword()!=null&&!newUser.getPassword().equals("")){
                oldUser.setPassword(encoder.encode(newUser.getPassword()));
                userDao.save(oldUser);
        }
    }

    /**
     * 修改用户信息除用户名和密码外
     * @param user
     */
    public void changeInfo(User user){
        User oldUser=userDao.findById(user.getId()).get();
        if(user.getBirthday()!=null&&!"".equals(user.getBirthday()))
        {
            oldUser.setBirthday(user.getBirthday());
        }
        if(user.getGender()!=null&&!"".equals(user.getGender()))
        {
            oldUser.setGender(user.getGender());
        }
        if(user.getPhoto()!=null&&!"".equals(user.getPhoto()))
        {
            oldUser.setPhoto(user.getPhoto());
        }
        if(user.getIntro()!=null&&!"".equals(user.getIntro()))
        {
            oldUser.setIntro(user.getIntro());
        }
        userDao.save(oldUser);
    }

}
